import { CommonModule } from '@angular/common';
import { ChangeDetectorRef, Component, DestroyRef, ElementRef, EventEmitter, inject, Input, OnInit, Output, TemplateRef, ViewChild } from '@angular/core';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { FormBuilder, FormControl, FormGroup, FormsModule, ReactiveFormsModule } from '@angular/forms';

import { OptionsInterface } from '@app/core/services/types';
import { SharedModule } from '@app/shared/shared.module';
import { NzSafeAny } from 'ng-zorro-antd/core/types';
import { NzDrawerModule } from 'ng-zorro-antd/drawer';
import { NzFormModule } from 'ng-zorro-antd/form';
import { NzGridModule } from 'ng-zorro-antd/grid';
import { NzInputNumberModule } from 'ng-zorro-antd/input-number';
import { NzResultModule } from 'ng-zorro-antd/result';
import { ColorPickerModule } from 'ngx-color-picker';

import { DataSourceSettingModalService } from './datasource-setting-modal/datasource-modal.service';
import { LinkActionSettingModalService } from './link-action-setting-modal/link-action-setting-modal.service';
import { WidgetSharedService } from '../widgetShared.service';
import { WidgetConfig } from '../widget-default-setting';

@Component({
  selector: 'app-config-panel',
  standalone: true,
  imports: [SharedModule, NzDrawerModule, NzResultModule, NzGridModule, NzInputNumberModule, ColorPickerModule],
  templateUrl: './config-panel.component.html',
  styleUrl: './config-panel.component.less'
})
export class ConfigPanelComponent implements OnInit {
  @Input() title: string = '';
  @Output() readonly setDrawerStatus = new EventEmitter();
  color = '#fafafa';
  fontColor = '#121621';
  upColor = 'rgb(224, 43, 43)';
  backColor = 'rgb(245, 166, 35)';
  backgroundColor = '#fafafa';
  _isDisplay: boolean = false;
  _destroyRef = inject(DestroyRef);
  _widget!: WidgetConfig;
  fontList: string[] = ['微软雅黑', '宋体', '黑体', '楷体', '隶书', '幼圆', '华文宋体', '华文仿宋', 'PingFang SC', 'Microsoft YaHei', 'Noto Sans SC'];
  directions: string[] = ['水平方向', '垂直方向'];
  fontWeightList: OptionsInterface[] = [
    { value: 300, label: '300 x 300' },
    { value: 400, label: '400 x 400' },
    { value: 500, label: '500 x 500' },
    { value: 600, label: '600 x 600' }
  ];
  dataFieldList: OptionsInterface[] = [];
  validateForm!: FormGroup;

  constructor(
    public readonly sharedService: WidgetSharedService,
    private readonly cdr: ChangeDetectorRef,
    private readonly fb: FormBuilder,
    private readonly lineActionSettingModalService: LinkActionSettingModalService,
    private readonly dataSourceSettingModalService: DataSourceSettingModalService
  ) {}

  /**
   * Defines if drop is enabled. `true` by default.
   */
  @Input() set isDisplay(value: boolean) {
    const configPanel: HTMLElement = document.querySelector('.right-panel')!;
    this._isDisplay = value;

    if (configPanel) {
      if (this._isDisplay === true) {
        configPanel.classList.toggle('drawer-open');
      } else {
        configPanel.classList.remove('drawer-open');
      }
    }
  }

  /**
   * Defines if selected is component or not..
   */
  @Input() set widget(value: WidgetConfig) {
    this._widget = value;
    this.setPanelValue();
  }

  ngOnInit(): void {
    this.sharedService.initWidget.subscribe((widget: WidgetConfig | null) => {
      this._widget = widget!;
      this.setPanelValue();
    });

    this.validateForm = this.fb.group({
      title: new FormControl(),
      value: new FormControl(),
      tag: new FormControl(),
      fontSize: new FormControl(),
      direction: new FormControl(),
      fontFamily: new FormControl(),
      fontWeight: new FormControl(),
      padding: new FormControl(),
      backgroundRadius: new FormControl(),
      contentMargin: new FormControl(),
      xyPos: new FormControl(),
      letterSpacing: new FormControl(),
      backgroundColor: new FormControl(),
      fontColor: new FormControl(),
      datatypeId: new FormControl(null, {
        asyncValidators: [],
        updateOn: 'blur'
      }),
      fieldName: new FormControl(null, {
        asyncValidators: [],
        updateOn: 'blur',
        validators: []
      })
    });
    this.setPanelValue();
  }

  isTableConfigProperty(): boolean {
    return this._widget.field === 'table';
  }

  isTextConfigProperty(): boolean {
    return this._widget.field === 'line-text' || this._widget.field === 'text';
  }

  setPanelValue(): void {
    if (this._widget) {
      this.validateForm.patchValue({ ...this._widget });
    }
  }

  propertyUpdate(propertyName: string): void {
    (this._widget as NzSafeAny)[propertyName] = this.validateForm.controls[propertyName].value;
    this.sharedService.widgetConfigChange(this._widget);
  }

  hideConfigPanel(): void {
    this.setDrawerStatus.emit(false);
  }

  editDataSource(): void {
    this.dataSourceSettingModalService
      .show({ nzTitle: '编辑数据源', nzWidth: '760px' }, this._widget['tableConfig'])
      .pipe(takeUntilDestroyed(this._destroyRef))
      .subscribe((result: NzSafeAny) => {
        const { modalValue, status } = result;
        if (status) {
          const { dataSourceList, customColumn } = modalValue;
          this._widget['tableConfig'] = { dataSourceList: dataSourceList, customColumn: customColumn };
          this.sharedService.widgetConfigChange(this._widget);
        }
      });
  }

  setAction(): void {
    this.lineActionSettingModalService
      .show({ nzTitle: '设置交互', nzWidth: '560px' }, this._widget['linkAction'] || null)
      .pipe(takeUntilDestroyed(this._destroyRef))
      .subscribe((result: NzSafeAny) => {
        const { modalValue, status } = result;
        if (status === 1) {
          const { linkUrl, type } = modalValue;
          switch (type) {
            case 1:
              this._widget['linkAction'] = { linkUrl: linkUrl, type: type };
              this.sharedService.widgetConfigChange(this._widget);
              break;
            case 2:
              this._widget['gotoTop'] = true;
              this.sharedService.widgetConfigChange(this._widget);
              break;
            default:
              break;
          }
        }
      });
  }
}
